package com.example.demo.demo.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * jdb连接数据库（驱动管理器）
 *
 * @author: htc
 * @date: Created in 15:10 2018/11/2.
 */
public class Demo {
    /**
     * jdbc协议:数据库子协议://主机:端口/数据库
     */
    final static String url = "jdbc:postgresql://10.110.91.114/idata_meta?&tcpKeepAlive=true&autoReconnect=true";
    final static String user = "postgres";
    final static String pwd = "mmp&H!^&zHCO8pR";

    public static void main(String[] args) throws Exception {
        connectDb();
        connectDb2();
        connectDb3();
    }

    /**
     * 方法一：从jar包中获取驱动
     *
     * @throws SQLException
     */
    public static void connectDb() throws SQLException {
        System.out.println("############################");
        //1、创建驱动程序类对象
        Driver driver = new org.postgresql.Driver();

        //2、链接数据库,返回连接对象
        Properties props = new Properties();
        props.setProperty("user", "postgres");
        props.setProperty("password", "mmp&H!^&zHCO8pR");
        Connection connection = driver.connect(url, props);

        System.out.println(connection);
    }

    /**
     * 方法二：使用驱动管理器链接数据库
     * @throws SQLException
     */
    public static void connectDb2() throws SQLException {
        System.out.println("############################");
        //1、驱动实例化的时候会自动注册到DriverManager中(可以注册多个驱动程序)
        Driver pg = new org.postgresql.Driver();
        Driver mysql = new com.mysql.jdbc.Driver();

        //2、链接到具体数据库,返回连接对象(根据URL中的协议获取相应的驱动)
        Connection connection = DriverManager.getConnection(url, user, pwd);

        System.out.println(connection);
    }



    /**
     * 方法三（常用）:
     * @throws SQLException
     */
    public static void connectDb3() throws SQLException, ClassNotFoundException {
        System.out.println("############################");
        //1、通过得到字节码对象的方式加载静态代码块，从而注册驱动程序
        Class.forName("org.postgresql.Driver");

        //2、链接到具体数据库,返回连接对象(根据URL中的协议获取相应的驱动)
        Connection connection = DriverManager.getConnection(url, user, pwd);

        System.out.println(connection);
    }
}
